package com.demo.test.other;

import okhttp3.*;
import org.junit.Test;

import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ApiClient111 {
//    private static final String APP_ID = "your-app-id";
    private static final String APP_ID = "2cda0a9ffe754f06";
    private static final String APP_SECRET = "54f098c4029f9b9ed4afa1b1ec34c7e7";
    private static final String BASE_URL = "http://localhost:8080";

    public static void sendRequest() throws Exception {
        // 1. 准备请求参数
        String path = "/openapi/api/v1/data";
        String method = "POST";
        String nonce = UUID.randomUUID().toString();
//        String nonce = "52e80f03-02d2-4c94-8fb9-124df5302ebc";
        long timestamp = System.currentTimeMillis();
//        String requestBody = "{\"key\":\"11111\"}";
        String requestBody = "{\"param1\":\"申屠刚\",\"param2\":10}";

        // 2. 生成签名
        String signature = HmacSigner.generateSignature(APP_SECRET,method, path, String.valueOf(timestamp),
                nonce, requestBody);

        // 3. 发送请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(BASE_URL + path)
                .post(RequestBody.create(requestBody, MediaType.get("application/json")))
                .header("X-App-Id", APP_ID)
                .header("X-Nonce", nonce)
                .header("X-Timestamp", String.valueOf(timestamp))
                .header("X-Signature", signature)
                .build();

        System.out.println("生成的签名为：" + signature);

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println("Response: " + response.body().string());
            } else {
                System.out.println("Error: " + response.code() + " - " + response.body().string());
            }
        }
    }

    @Test
    public void m1(){
        long startTime = System.currentTimeMillis();

        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    sendRequest();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }, 0, 1, TimeUnit.SECONDS);

        long endTime = System.currentTimeMillis();
        System.out.println("执行耗时["+(endTime - startTime)+"]毫秒");
    }


}